/*
 * @Author: xiaosihan 
 * @Date: 2021-12-21 09:52:52 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2022-02-15 15:41:04
 */

import SpriteText from "three-base/SpriteText";
import btnBgPNG from "./btnBg.png";


export default class Btn extends SpriteText {

    constructor(text?: string) {
        super(Btn.completion(text));
        this.borderColor = "#f00";
        this.borderWidth = 0;
        this.borderRadius = 0;

        this.fontSize = 100;
        this.padding = 10;

        this.init();
    }

    customScale = 1;

    // 动态背景纹理
    // static btnBg = new ApngTexture(btnBgPNG);

    static btnBg = (() => {
        const img = new Image();
        img.src = btnBgPNG;
        return img;
    })();

    // 使用空格补全字符长度
    static completion(text: string = "") {
        const textLength = text.length;
        const spaceLength = Math.ceil((10 - textLength) * 2);
        const space = new Array(spaceLength).fill(" ").join("");
        return `${space}${text}${space}`;
    }

    init() {
        this.material.alphaTest = 0.2;
    }

    _genCanvas() {
        // @ts-ignore
        super._genCanvas();

        this.drawBg();
    }

    async drawBg() {

        while (!Btn.btnBg.complete) {
            await new Promise(resolve => setTimeout(resolve, 200));
        }

        //@ts-ignore
        const canvas = this._canvas as HTMLCanvasElement;
        const { width: btnBgWidth, height: btnBgHeight } = Btn.btnBg;
        const { width, height } = canvas;
        const ctx = canvas.getContext("2d")!;
        ctx.globalCompositeOperation = "destination-over";
        ctx.drawImage(Btn.btnBg, 0, 0, btnBgWidth, btnBgHeight, this.padding * -10, this.padding * -10, width, height);
    }

    cursor = "pointer";

    onClick?: () => void;

    renderOrder = 9;

    onBeforeRender = () => {
        this._genCanvas();
        this.scale.multiplyScalar(this.customScale);
    }

}

